package dao

import (
	"gorm.io/gorm"
	"log"
	"writerhelper/global"
	"writerhelper/model"
	"writerhelper/params"
)

type BookDao struct {
	*gorm.DB
}

func (bd *BookDao) CreateBook(u *model.User, email string) bool {

	//直接创建了书籍
	createRes := global.MysqlDB.Create(&model.Book{
		BookName: u.Books[0].BookName,
		Outline:  u.Books[0].Outline,
		UserID:   u.ID,
	})
	if createRes.Error != nil {
		log.Println(createRes.Error)
		return false
	} else {
		return true
	}

}

func (bd *BookDao) FindBookInfo(data string) []model.Book {
	userEmail := map[string]interface{}{}
	var bookinfoes []model.Book
	res := global.MysqlDB.Model(&model.User{}).Where("email = ?", data).First(&userEmail).Error
	if res != nil {
		log.Fatal("无此用户: ", res.Error())

	}
	newRes := global.MysqlDB.Where("book_id = ?", userEmail["id"]).First(&bookinfoes)
	if newRes.Error != nil {
		log.Fatal("查询书籍的时候出现问题： ", newRes.Error)
	}
	return bookinfoes

}

func DeleteBook(bookname string) error {
	//根据bookname进行删除
	var book model.Book
	if err := global.MysqlDB.Where("book_name = ?", bookname).Delete(&book).Error; err != nil {
		return err
	}
	return nil
}

func (bd *BookDao) FindWriter(params params.ChangeBookInfo) *model.User {
	var user model.User
	bd.Model(&model.User{}).Where("email = ?", bd.Table("books").Select("book_id").Find(&user)
}
